use std::sync::OnceLock;

use rusqlite::Connection;

use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;
use crate::state;

static mut MAIN: OnceLock<Connection> = OnceLock::new();

pub(crate) fn main() -> &'static mut Connection {
    connect().expect("无法获取数据库连接");

    unsafe { MAIN.get_mut().unwrap() }
}

pub(crate) fn connect() -> MagicBoxResult<()> {
    // 检查，不可重复调用
    unsafe {
        if MAIN.get().is_some() {
            return Ok(());
        }
    }

    let data_path = state::application::app().path_resolver().app_local_data_dir();
    if data_path.is_none() {
        return Err(MagicBoxError::new(Code::UndefinedError, "无法获取应用本地数据目录"));
    }

    let db_path = data_path.unwrap().join("main.db");

    // 连接数据库
    let connection = Connection::open(db_path.clone());
    if connection.is_err() {
        return Err(MagicBoxError::new(Code::UndefinedError, format!("无法打开数据库文件: {}", db_path.to_str().unwrap()).as_str()));
    }

    unsafe {
        MAIN.set(connection.unwrap()).expect("初始化数据库连接失败");
    }

    Ok(())
}

pub(crate) mod components {
    use rusqlite::Connection;

    pub(crate) mod v2ray {
        use std::sync::OnceLock;

        use rusqlite::Connection;

        use crate::runtime::error::MagicBoxError;
        use crate::runtime::response::Code;
        use crate::runtime::result::MagicBoxResult;
        use crate::state;

        pub(super) static mut COMPONENT_V2RAY: OnceLock<Connection> = OnceLock::new();

        pub(crate) fn connect() -> MagicBoxResult<()> {
            // 检查，不可重复调用
            unsafe {
                if COMPONENT_V2RAY.get().is_some() {
                    return Ok(());
                }
            }

            let data_path = state::application::app().path_resolver().app_local_data_dir();
            if data_path.is_none() {
                return Err(MagicBoxError::new(Code::UndefinedError, "无法获取应用本地数据目录"));
            }

            let db_path = data_path.unwrap().join("components.v2ray.db");

            // 连接数据库
            let connection = Connection::open(db_path.clone());
            if connection.is_err() {
                return Err(MagicBoxError::new(Code::UndefinedError, format!("无法打开数据库文件: {}", db_path.to_str().unwrap()).as_str()));
            }

            unsafe {
                COMPONENT_V2RAY.set(connection.unwrap()).expect("初始化数据库连接失败");
            }

            Ok(())
        }
    }

    pub(crate) fn v2ray() -> &'static mut Connection {
        v2ray::connect().expect("无法获取数据库连接");

        unsafe { v2ray::COMPONENT_V2RAY.get_mut().unwrap() }
    }
}


